package com.syq.service.impl;

import com.syq.constant.CacheConstants;
import com.syq.constant.StrategyConstants;
import com.syq.feign.CacheFeign;
import com.syq.model.StandardSubmit;
import com.syq.service.FilterChainService;
import com.syq.util.PushMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName: FeeFilterServiceImpl
 * @Description: TODO
 * @Create by: syq
 * @Date: 2022/8/27 9:52
 */
@Slf4j
@Service("fee")
public class FeeFilterServiceImpl implements FilterChainService {
    @Autowired
    private CacheFeign cacheFeign;

    @Autowired
    private PushMsgUtil pushMsgUtil;

    @Override
    public boolean strategy(StandardSubmit standardSubmit) {
        Integer clientID = standardSubmit.getClientID();
        String key= CacheConstants.CACHE_PREFIX_CLIENT+clientID;
        Long fee = Long.valueOf(cacheFeign.hget(key, "fee"));
        Long price = standardSubmit.getFee();
        if (fee>0) {
            if (fee>price){
                Long fee1 = cacheFeign.hincr(key, "fee", -price);
                if (fee1<0){
                    Long fee2 = cacheFeign.hincr(key, "fee", price);
                    pushMsgUtil.sendLog(standardSubmit, StrategyConstants.STRATEGY_ERROR_FEE);
                    pushMsgUtil.pushReport(standardSubmit, StrategyConstants.STRATEGY_ERROR_FEE);
                    log.error("[策略模块 - 扣费策略] 扣费策略执行失败。。。用户剩余金额不足。。。");
                    return false;
                }
                cacheFeign.incr(CacheConstants.CACHE_PREFIX_CUSTOMER_FEE+clientID,price);
                log.info("[策略模块 - 扣费策略]扣费策略执行成功");
                return true;
            }
        }
        pushMsgUtil.sendLog(standardSubmit, StrategyConstants.STRATEGY_ERROR_FEE);
        pushMsgUtil.pushReport(standardSubmit, StrategyConstants.STRATEGY_ERROR_FEE);
        return false;
    }
}
